/**
 * Copyright (c) subnew ;
 * email:joseanluo@gmail.com;
 * Licensed under the GPL;  
 * @Title: ValidateCodeServlet.java;
 * @Package com.subnew.framework.web.servlet;
 */
package com.subnew.mango.frame.web.listener;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.subnew.mango.frame.constant.Globals;
import com.subnew.mango.frame.constant.RandomCodeEnum;
import com.subnew.mango.frame.utils.ProjectResourceUtil;


/**
 * 随机生成验证码图片
 * 
 * @author JoseanLuo
 * @date 2014-7-16 上午8:41:43
 * @history new
 * @version V1.0
 */
@SuppressWarnings("serial")
public class ValidateCodeServlet extends HttpServlet {
	private static final String RAND_CODE_TYPE = ProjectResourceUtil.getValueWithDefault("randCodeType", "1");
	private static final int RAND_CODE_LENGTH = Integer.parseInt(ProjectResourceUtil.getValueWithDefault("randCodeLength", "4"));
	/**
	 * 干扰线
	 */
	private static final int count = 200;

	/**
	 * 定义图形大小
	 */
	private static final int width = 105;
	/**
	 * 定义图形大小
	 */
	private static final int height = 35;
	/**
	 * 干扰线的长度=1.414*lineWidth
	 */
	private static final int lineWidth = 2;

	/**
	 * 处理Get请求
	 */
	@Override
	public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		// 设置页面不缓存
		response.setHeader("pragma", "No-Cache");
		response.setHeader("Coche-Control", "No-Cache");
		response.setDateHeader("Expires", 0);

		// 在内存中创建图象
		final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 获取图形上下文
		final Graphics2D graphics = (Graphics2D) image.getGraphics();

		// 设定背景颜色
		graphics.setColor(Color.WHITE); // ---1
		
		// 设定边框
		graphics.fillRect(0, 0, width, height);
		graphics.drawRect(0, 0, width - 1, height - 1);// ---2

		final Random random = new Random();
		// 随机产生干扰线，使图象中的认证码不易被其它程序探测到
		for (int i = 0; i < count; i++) {
			graphics.setColor(getRandColor(150, 200)); // ---3

			final int x = random.nextInt(width - lineWidth - 1) + 1; // 保证画在边框之内
			final int y = random.nextInt(height - lineWidth - 1) + 1;
			final int xl = random.nextInt(lineWidth);
			final int yl = random.nextInt(lineWidth);
			graphics.drawLine(x, y, x + xl, y + yl);
		}

		// 取随机产生的认证码
		final String resultCode = extractRandomCode();
		for (int i = 0; i < resultCode.length(); i++) {
			// 设置字体颜色
			graphics.setColor(Color.BLACK);
			// 设置字体样式
			graphics.setFont(new Font("Times New Roman", Font.BOLD, 24));
			// 设置字符，字符间距，上边距
			graphics.drawString(String.valueOf(resultCode.charAt(i)), (23 * i) + 8, 26);
		}

		// 将认证码存入SESSION
		request.getSession().setAttribute(Globals.SESSION_KEY_OF_RAND_CODE, resultCode);
		// 图象生效
		graphics.dispose();
		// 输出图象到页面
		ImageIO.write(image, "JPEG", response.getOutputStream());

	}

	/**
	 * 处理Post请求
	 */
	@Override
	public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	private String extractRandomCode() {
		switch (RAND_CODE_TYPE.charAt(0)) {
		case '1':
			return RandomCodeEnum.NUMBER_CHAR.genarateCode(RAND_CODE_LENGTH);
		case '2':
			return RandomCodeEnum.LOWER_CHAR.genarateCode(RAND_CODE_LENGTH);
		case '3':
			return RandomCodeEnum.UPPER_CHAR.genarateCode(RAND_CODE_LENGTH);
		case '4':
			return RandomCodeEnum.LETTER_CHAR.genarateCode(RAND_CODE_LENGTH);
		case '5':
			return RandomCodeEnum.ALL_CHAR.genarateCode(RAND_CODE_LENGTH);
		default:
			return RandomCodeEnum.NUMBER_CHAR.genarateCode(RAND_CODE_LENGTH);
		}

	}
	
	/**
	*  取得给定范围随机颜色
	* @param fc 小
	* @param bc 大
	* @return   随机颜色
	* @author JoseanLuo  
	* @date 2014-7-17 上午12:48:28
	* @version V1.0
	 */
	private Color getRandColor(int fc, int bc) { //
		final Random random = new Random();
		if (fc > 255) {
			fc = 255;
		}
		if (bc > 255) {
			bc = 255;
		}

		final int r = fc + random.nextInt(bc - fc);
		final int g = fc + random.nextInt(bc - fc);
		final int b = fc + random.nextInt(bc - fc);

		return new Color(r, g, b);
	}
}
